#!/usr/bin/env python3
"""主应用 - Emby媒体库展示面板"""

import asyncio
import json
import yaml
import os
import sys
import logging

# 添加项目根目录到Python路径，以便能够导入embytools模块
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from aiohttp import web
import aiohttp_cors
from embytools.emby_client import EmbyClient
# 导入数据管理器
from dashboard.data_manager import get_data_manager
from dashboard.library_list_page_handler import router as library_list_page_router, set_data_manager as set_library_list_data_manager
from dashboard.phone_playlist_page_handler import router as phone_playlist_page_router, set_data_manager as set_phone_playlist_data_manager
from dashboard.douyin_source_handler import router as douyin_source_router, set_data_manager as set_douyin_source_data_manager
from dashboard.settings_page_handler import router as settings_router, set_data_manager as set_settings_data_manager
from dashboard.sync_scheduler import scheduler as sync_scheduler_task

# 获取数据管理器实例
data_manager = get_data_manager()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 全局变量
emby_client = None

async def get_libraries_handler(request):
    """获取媒体库列表"""
    try:
        # 使用数据管理器获取媒体库列表（带缓存）
        libraries = await data_manager.get_libraries()
        
        return web.json_response({
            'success': True,
            'libraries': libraries
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

async def refresh_libraries_handler(request):
    """手动刷新媒体库列表"""
    try:
        # 使用数据管理器强制刷新媒体库列表
        libraries = await data_manager.get_libraries(force_refresh=True)
        
        return web.json_response({
            'success': True,
            'message': '媒体库数据已刷新',
            'libraries_count': len(libraries)
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

async def check_playlist_status_handler(request):
    """检查播放列表状态"""
    try:
        data = await request.json()
        playlist_name = data.get('playlist_name')
        
        if not playlist_name:
            return web.json_response({
                'success': False,
                'error': '缺少播放列表名称'
            }, status=400)
        
        exists = await emby_client.check_playlist_exists(playlist_name)
        
        return web.json_response({
            'success': True,
            'exists': exists
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

async def get_data_files_handler(request):
    """获取data目录下的文件列表"""
    try:
        # 获取项目根目录下的data路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        data_dir = os.path.join(project_root, 'data')
        
        if not os.path.exists(data_dir):
            return web.json_response({
                'success': False,
                'error': 'data目录不存在'
            }, status=404)
        
        # 递归获取所有文件
        files_list = []
        for root, _, files in os.walk(data_dir):
            for file in files:
                if file.endswith('.json'):  # 只返回JSON文件
                    # 获取相对路径
                    relative_path = os.path.relpath(os.path.join(root, file), data_dir)
                    files_list.append(relative_path)
        
        return web.json_response({
            'success': True,
            'files': files_list,
            'total': len(files_list)
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

async def get_data_file_content_handler(request):
    """直接获取特定数据文件的原始内容（支持直接下载）"""
    try:
        # 获取文件路径参数
        file_path = request.match_info.get('file_path', '').strip()
        
        # 安全检查：防止路径遍历攻击
        if '..' in file_path:
            return web.HTTPBadRequest(text='非法的文件路径')
        
        # 构建完整文件路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        full_path = os.path.join(project_root, 'data', file_path)
        
        if not os.path.exists(full_path):
            return web.HTTPNotFound(text='文件不存在')
        
        if not full_path.endswith('.json'):
            return web.HTTPBadRequest(text='只支持JSON文件')
        
        # 直接返回文件内容，设置适当的Content-Type和Content-Disposition
        # 读取文件原始内容而不进行JSON解析
        with open(full_path, 'rb') as f:
            content = f.read()
        
        # 创建响应对象，设置为JSON类型，并支持直接下载
        response = web.Response(body=content)
        response.content_type = 'application/json'
        # 获取文件名作为下载文件名
        filename = os.path.basename(full_path)
        response.headers['Content-Disposition'] = f'inline; filename="{filename}"'
        response.headers['Content-Length'] = str(len(content))
        
        return response
    except Exception as e:
        return web.HTTPInternalServerError(text=f'服务器内部错误: {str(e)}')

async def start_sync_scheduler():
    """启动同步调度器作为后台任务"""
    try:
        print("🔄 启动定时同步调度器...")
        # 作为后台任务运行调度器
        asyncio.create_task(sync_scheduler_task())
        print("✅ 定时同步调度器已启动")
    except Exception as e:
        print(f"❌ 启动定时同步调度器失败: {e}")


async def start_server():
    """启动Web服务器"""
    # 加载配置
    data_manager.load_config()
    
    # 初始化Emby客户端
    global emby_client
    emby_client = await data_manager.get_emby_client()
    
    # 设置数据管理器到各页面处理器
    if emby_client:
        set_library_list_data_manager(data_manager)
        set_phone_playlist_data_manager(data_manager)
        set_douyin_source_data_manager(data_manager)
        set_settings_data_manager(data_manager)
        
        # 预加载数据到缓存中，确保用户第一次访问就能立即获取数据
        print("📊 正在预加载媒体库数据到缓存...")
        await data_manager.get_libraries(force_refresh=True)
        print("✅ 媒体库数据预加载完成，缓存已就绪")
    
    app = web.Application()
    
    # 设置路由
    # 使用外部的媒体库列表页面处理器
    app.add_routes(library_list_page_router)
    app.router.add_get('/api/libraries', get_libraries_handler)
    app.router.add_get('/api/libraries/refresh', refresh_libraries_handler)
    app.router.add_post('/api/check-playlist-status', lambda request: check_playlist_status_handler(request) if emby_client else web.json_response({'success': False, 'error': 'Emby客户端未初始化'}, status=500))
    
    # 数据文件API接口
    app.router.add_get('/api/data/files', get_data_files_handler)
    app.router.add_get('/api/data/files/{file_path:.*}', get_data_file_content_handler)
    
    # 注册手机播放列表页面路由
    app.add_routes(phone_playlist_page_router)
    
    # 注册抖音数据源路由
    app.add_routes(douyin_source_router)
    
    # 注册设置页面路由
    app.add_routes(settings_router)
    
    # 添加静态文件路由 - 先确保目录存在
    static_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
    os.makedirs(static_path, exist_ok=True)
    app.router.add_static('/static/', path=static_path, name='static')
    
    # 配置CORS
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
        )
    })
    
    # 为所有路由启用CORS
    for route in list(app.router.routes()):
        cors.add(route)
    
    runner = web.AppRunner(app)
    await runner.setup()
    
    site = web.TCPSite(runner, '0.0.0.0', 8082)
    await site.start()
    
    # 启动同步调度器
    await start_sync_scheduler()
    
    print("🚀 模块化Emby媒体库展示面板已启动!")
    print("📊 访问地址: http://0.0.0.0:8082")
    print("📱 新增功能: 手机播放列表管理")
    print("🎵 新增功能: 抖音数据源配置")
    print("🔄 新增功能: 定时同步调度器")
    print("⚙️ 新增功能: 服务器设置页面")
    print("💡 模块化结构:")
    print("   - dashboard/main.py: 主应用")
    print("   - dashboard/phone_playlist_handler.py: 手机播放列表处理器")
    print("   - dashboard/douyin_source_handler.py: 抖音数据源处理器")
    print("   - dashboard/settings_page_handler.py: 服务器设置页面处理器")
    print("   - dashboard/sync_scheduler.py: 同步调度器")
    
    # 保持服务器运行
    await asyncio.Future()

if __name__ == "__main__":
    try:
        asyncio.run(start_server())
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")